# -*- coding: utf-8 -*-
# @Author: Administrator
# @Date:   2022-11-10 10:05:27
# @Last Modified by:   Administrator
# @Last Modified time: 2022-11-10 15:10:14
import time
import json
import requests
import os
from copy import deepcopy
from flask import Blueprint, request, jsonify
from controllers.config import *
from controllers.common import *
from controllers.db import *

growth_gift_project_down_api = Blueprint('growth_gift_project_down_api', __name__)
growth_gift_project_action_api = Blueprint('growth_gift_project_action_api', __name__)
growth_gift_project_upload_api = Blueprint('growth_gift_project_upload_api', __name__)


@growth_gift_project_down_api.route('/growth_gift_project_down/<int:is_push>', methods=['GET', 'POST'])
def growth_gift_project_down(is_push):
    query = GrowthGiftProject.query.order_by('project').all()
    # deal data
    res = {}
    for que in query:
        dic_item = {
            "basic": json.loads(que.basic),
            "level_task_list": json.loads(que.level_task_list),
            "remark": que.remark
        }
        for index in range(len(dic_item['level_task_list'])):
            reward_list = RewardToTMysqlNew(dic_item['level_task_list'][index]['reward'])
            dic_item['level_task_list'][index]['reward'] = reward_list
        res[str(que.project)] = dic_item
    if is_push == 0:
        response = DownLoad("growth_gift_project", res, is_push)
        return response
    elif is_push == 1:
        response = DownLoad('growth_gift_project', res, is_push)
        return response
    # return {}


@growth_gift_project_action_api.route('/growth_gift_project_action', methods=['POST'])
def growth_gift_project_action():
    update_data = json.loads(request.data)
    result = {'msg': '成功', 'ret': 0, }
    _type = update_data['type']
    project = update_data['project']

    project_data = GrowthGiftProject.query.filter_by(project=project).first()

    if _type == 'remark':
        remark = update_data['remark']
        project_data.remark = str(remark)
        db.session.commit()

    elif _type == 'basic':
        basic_data = json.loads(project_data.basic)
        result['basic_data'] = basic_data

    elif _type == 'update_basic':
        basic_data = update_data['basic_data']
        project_data.basic = json.dumps(basic_data)
        db.session.commit()

    elif _type == 'task_and_reward':
        reward_list = json.loads(project_data.level_task_list)
        for i in range(len(reward_list)):
            node = reward_list[i]
            node['idx'] = i
        result['goal_reward'] = reward_list

    elif _type == 'update_task_and_reward':
        reward_list = update_data['goal_reward']
        project_data.level_task_list = json.dumps(reward_list)
        db.session.commit()
        result['msg'] = '更新成功'

    elif _type == 'iap_list':
        with open(STATIC_PATH + 'iap_list.json') as f:
            data = json.load(f)
            for i in data:
                i['value'] = i['gem']
                i['label'] = i['label'] + ' - ' + str(i['gem'])
            return json.dumps(data)

    return jsonify(result)


@growth_gift_project_upload_api.route('/growth_gift_project_upload', methods=['GET'])
def growth_gift_project_upload():
    with open(STATIC_PATH + 'growth_gift_project.json', encoding='utf8') as f:
        file_data = json.load(f)
    print(file_data)
    query = GrowthGiftProject.query.order_by('project').all()
    project_list = []
    for query_item in query:
        project_list.append(query_item.project)
    print(project_list)
    for project in file_data:
        need_data = {}
        need_data[str(project)] = file_data[str(project)]
        format_res = format_data(need_data)
        print('format', format_res)
        if int(project) in project_list:
            project_data = GrowthGiftProject.query.filter_by(project=project).first()
            project_data.basic = json.dumps(format_res['basic'])
            project_data.remark = format_res['remark']
            project_data.level_task_list = json.dumps(format_res['level_task_list'])
        else:
            print(int(project))
            print(format_res['basic'])
            print(format_res['remark'])
            print(format_res['level_task_list'])
            new_project_data = GrowthGiftProject(
                project=int(project),
                basic=json.dumps(format_res['basic']),
                remark=format_res['remark'],
                level_task_list=json.dumps(format_res['level_task_list'])
            )
            db.session.add(new_project_data)
        db.session.commit()
        return {}


def format_data(growth_obj):
    key = list(growth_obj.keys())[0]
    project = int(key)
    basic = growth_obj[str(key)]['basic_data']
    remark = ''
    level_task_list = []
    level_list = growth_obj[str(key)]['level_task_list']
    for level_item in level_list:
        target_level = level_item['target_level']
        reward = []
        for reward_item in level_item['reward']:
            reward.append({
                'type': reward_item['a'][0],
                'id': reward_item['a'][1],
                'num': reward_item['a'][2]
            })
        level_task_list.append({
            'target_level': target_level,
            'reward': reward
        })
    return {
        'project': project,
        'basic': basic,
        'remark': remark,
        'level_task_list': level_task_list
    }
